package com.zhx.sweet.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义的认证成功类
 *
 * spring security 在认证成功的时候默认跳转到原本的请求的地方  现在需要自定义请求成功后返回用户信息
 *
 * 可以实现 AuthenticationSuccessHandler
 * 也可以继承 SavedRequestAwareAuthenticationSuccessHandler spring默认的成功处理器
 *
 * 完成后需要注入到config中去 并且配置自己的成功处理器
 *
 * @author zhx
 * @create 2017-11-02 11:24
 **/
@Component("myAuthentionSuccessHandler")
public class MyAuthentionSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private  final static Logger logger = LoggerFactory.getLogger(MyAuthentionSuccessHandler.class);

    //spring 启动的时候自动注册的一个mapper 可以转换类
    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    @ConditionalOnMissingBean(name = "cuestomWebAuthentionSuccessHandler")
    public CuestomAuthentionSuccessHandler CuestomAuthentionSuccessHandler(){
        return new DefaultCuestomAuthentionSuccessHandler();
    }

    @Autowired
    private CuestomAuthentionSuccessHandler cuestomAuthentionSuccessHandler;

    //Authentication 其中一个核心接口  基本上包含了所有需要的信息
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try{
            cuestomAuthentionSuccessHandler.onAuthenticationSuccess(request,response,authentication);
        }catch(Exception e){
            logger.error(e.getMessage());
        }
    }
}
